<template>
  <div>
    <!-- 面包屑导航区域 -->
    <bread-crumb :breadContent="breadContent"></bread-crumb>

    <!-- 搜索与添加区域 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入内容" v-model="queryInfo.key" clearable @clear="getFilesList">
          <el-button slot="append" icon="el-icon-search" @click="getFilesList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <!-- <el-button type="primary" @click="addDialogVisible = true">上传文件</el-button> -->
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers = "getAuthHeaders()"
          :show-file-list="false"
          :on-success="handleFileSuccess">
          <!-- <img v-if="addForm.file" :src="addForm.file" class="avatar"> -->
          <el-button type="primary">上传文件</el-button>
        </el-upload>
      </el-col>
    </el-row>
    <br/>

    <!-- 卡片视图 -->
    <el-card>
      <el-table :data="fileList" border stripe :max-height="pageHeight">
        <el-table-column align="center" type="index"></el-table-column>
        <el-table-column align="center" label="文件名称"  prop="fileName"></el-table-column>
        <el-table-column align="center" label="文件ID" width="300" prop="id"></el-table-column>
        <!-- <el-table-column align="center" label="文件对象类型" width="120" prop="type"></el-table-column> -->
        <!-- <el-table-column align="center" label="对象名" prop="objectName"></el-table-column> -->
        <el-table-column align="center" label="桶名称" width="100" prop="bucketName"></el-table-column>
        <!-- <el-table-column align="center" label="文件前缀" width="100" prop="prefix"></el-table-column> -->
        <el-table-column align="center" label="文件名后缀" width="100" prop="suffix"></el-table-column>
        <el-table-column align="center" label="上传人" width="100" prop="uploader"></el-table-column>
        <el-table-column width="120px" label="操作" align="center">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="下载文件" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-download" size="mini" @click="downloadFileById(scope.row.id)" ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除文件" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeFileById(scope.row.id)" ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination  
      v-show="total>0" 
      :total="total" 
      :page.sync="queryInfo.page" 
      :limit.sync="queryInfo.size" 
      @pagination="getFilesList"/>
    </el-card>
  </div>
</template>

<script>
  export default {
    inject:['reload'],
    data(){
      return{
        breadContent:["超管设置","文件管理"],
        queryInfo: {
          key: '',
          page: 1,  // 当前的页数
          size: 10  // 当前每页显示多少条数据
        },
        total:0,
        fileList:[],
        upFileList:[],
      }
    },
    created(){
      this.getFilesList()
    },
    methods:{
      // 获取文件列表
      
      async getFilesList(){
        const { data: res } = await this.$http.get('os/page',{params: this.queryInfo})
        if (res.status !== 200) {
          return this.$message.error(res.message)
        }
        console.log(res.data.records)
        this.fileList = res.data.records
        this.total = res.data.total
      },

      // 上传文件成功的回调函数
      handleFileSuccess(res,file){
        //  console.log(res,file)
        this.$message.success('上传文件成功！')
        this.getFilesList()
        this.reload()
      },
     
      // 下载文件
      // async downloadFileById(id){
      //   console.log("获取文件列表")
      //   const { data: res } = await this.$http.get(`os/download?id=${id}`)
      //   console.log(res)
      //   if (res.status !== 200) {
      //     return this.$message.error(res.message)
      //   }
      //   console.log(res)
      //   this.reload()
      // },


      async downloadFileById(id){


        this.$http({
          method: 'GET',
            url: `os/download?id=${id}`,
            timeout: 3000,
            headers: {},
            // data: options.method.toLowerCase() !== 'get' ? options.data : undefined,
            responseType: 'blob'
          }).then(
            res => {
                const data = res.data
                // 有可能下载失败，比如返回{code: 0},但设置了responseType: 'blob'，axios会把data强制转为blob，导致下载undefined.excel（后缀取决于文件类型，这里只是举例）
                // 解决：将已转为blob类型的data转回json格式，判断是否下载成功
                const r = new FileReader()
                r.onload = function () {
                // 如果JSON.parse(this.result)不报错，说明this.result是json字符串，则可以推测是下载报错情况下返回的对象，类似于{code: 0}
                // 如果JSON.parse(this.result)报错，说明是下载成功，返回的二进制流，则进入catch进行后续处理
                console.log(res)
                try {
                  const resData = JSON.parse(this.result) // this.result为FileReader获取blob数据转换为json后的数据，即后台返回的原始数据
                  // 如果执行到这里，说明下载报错了，进行后续处理
                } catch (err) {
                  // 下载正常处理
                  let fileName = res.headers['content-disposition']
                  // 获取文件名
                  if (fileName && fileName.length >= 2) {
                    fileName = fileName.split('=')[1]
                  }
                  fileName = decodeURIComponent(fileName)
                  // 兼容ie11
                  if (window.navigator.msSaveOrOpenBlob) {
                    try {
                      const blobObject = new Blob([data])
                      window.navigator.msSaveOrOpenBlob(blobObject, fileName)
                    } catch (e) {
                      console.log(e)
                    }
                    return
                  }
                  // a标签实现下载
                  let url = window.URL.createObjectURL(new Blob([data]))
                  let link = document.createElement('a')
                  link.style.display = 'none'
                  link.href = url
                  link.setAttribute('download', fileName)
                  document.body.appendChild(link)
                  link.click()
                  // resolve(fileName)
                }
              }
              r.readAsText(data) // FileReader的API
            }).catch(res => {
              console.log(res)
            })
      },

      // 20210601-bps
      XHRLoadLoadFile:(url, data)=>{
      let xhr = new XMLHttpRequest()
      xhr.open('post',url)
      //如果需要请求头中这是token信息可以在这设置
      xhr.setRequestHeader('Content-Type','application/json;charset=UTF-8')
      xhr.responseType = 'blob'
      xhr.send(JSON.stringify(data))
      xhr.onreadystatechange = function(){
        if(xhr.readyState ===4 && xhr.status === 200){
          const blob = new Blob([xhr.response])
          let url = window.URL.createObjectURL(blob)
    
          //创建一个a标签元素，设置下载属性，点击下载，最后移除该元素
          let link = document.createElement('a')
          link.href = url
          link.style.display = 'none'
          //取出下载文件名
          const fileName = xhr.getResponseHeader('filename')
          const downlaodFileName = decodeURIComponent(fileName)
    
          link.setAttribute('download',downlaodFileName)
          link.click()
          window.URL.revokeObjectURL(url)
          }
        }
        },

      // 删除文件
      async removeFileById(id){
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data: res } = await this.$http.delete(`os/?id=${id}`)
          if(res.status !== 200) return this.$message.error('删除失败!')
          this.$message.success('删除成功!');
          this.getFilesList()
        }).catch(() => {this.$message.info('已取消删除')});
      }
    }
  }
</script>

<style lang="less" scoped>

</style>